package util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

import javax.imageio.ImageIO;

import org.lwjgl.opengl.Display;

import ui.UIConst;

public class ScreenshotWriter implements Runnable
{

	private File file;
	private ByteBuffer buffer;
	public ScreenshotWriter(File f, ByteBuffer b)
	{
		this.file = f;
		this.buffer = b;
	}

	public void run()
	{
		int width = UIConst.APP_WIDTH;
		int height = UIConst.APP_HEIGHT;
		int bpp = 4; // assumption here is that the display is 32-bit thus we have a byte per rgba
		
        // prepare the image for writing
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++)
        {
        	for (int y = 0; y < height; y++)
        	{
        		int i = (x + (width * y)) * bpp;
        		int r = buffer.get(i) & 0xFF;
        		int g = buffer.get(i + 1) & 0xFF;
        		int b = buffer.get(i + 2) & 0xFF;
        		image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b);
        	}
        }

        // append the correct format
        String path = file.getAbsolutePath();
        File image_file = new File(path + "." + UIConst.SCREENSHOT_FORMAT);
        
        // actually write the image
        try { ImageIO.write(image, "PNG", image_file); }
        catch(IOException err) { err.printStackTrace(); }
	}

}
